package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.log.LogAnno;
import com.itheima.pojo.Result;
import com.itheima.pojo.*;
import com.itheima.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Set;

@RestController
@RequestMapping("/user")
public class UserController {

     @Reference
    UserService userService;
    @LogAnno("获取用户名")
    @RequestMapping("/getCurrentUserName")
    public Result getCurrentUserName() {
        try {
            org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return Result.success("获取用户名成功", user.getUsername());
        } catch (Exception e) {
            return Result.error("获取用户名失败");
        }
    }

    @RequestMapping("/findAll")
    public PageResult findAll(@RequestBody QueryPageBean queryPageBean){

        return userService.findAll(queryPageBean);
    }
    @RequestMapping("/add")
    public Result add(@RequestBody User user){
        try {
            userService.add(user);
            return new Result(true,"新增用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"新增用户失败");
        }
    }

    @RequestMapping("/findAllRole")
    public Result findAllRole(){
        try {
            Set<Role> roles= userService.findAllRole();
            return Result.success("回显角色信息成功",roles);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("回显角色信息失败");
        }
    }
    @RequestMapping("/findUserById")
    public Result findUserById(Integer id){

           UserEditVo userEditVo =  userService.findUserById(id);

           return Result.success("",userEditVo);
    }
    @RequestMapping("/edit")
    public Result edit(@RequestBody User user){

        try {
            userService.edit(user);
            return Result.success("编辑成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.success("编辑失败");
        }

    }
    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            userService.delete(id);
            return Result.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.success("删除失败,存在引用");
        }
    }
}
